class Api::V1::BaseController < ApplicationController
  include Pundit

  # 捕获认证授权失败的报错
  rescue_from Pundit::NotAuthorizedError, with: :deny_access

  def deny_access
    api_error(status: 403, msg: '认证失败')
  end

  attr_accessor :current_user

  def authenticate_user!
    token, options = ActionController::HttpAuthentication::Token.token_and_options(request)
    user_email = options.blank? ? nil : options[:email]
    user = user_email && User.find_by(email: user_email)

    if user && ActiveSupport::SecurityUtils.secure_compare(user.authentication_token, token)
      self.current_user = user
    else
      return unauthenticated!
    end
  end

  def unauthenticated!
    api_error(status: 401, msg: '认证失败')
  end

  # 分页
  def paginate(resource)
    # 页码默认1
    resource = resource.page(params[:page] || 1)

    # 如果有分页量
    if params[:per_page]
      resource = resource.per(params[:per_page])
    end

    return resource
  end
end
